package com.ship.boats.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ship.boats.business.impl.BoatsSystemServiceImpl;
import com.ship.boats.domain.IhsShipBase;
import com.ship.boats.domain.SpBoastPortMessage;
import com.ship.boats.domain.SpBoatsArchivesExtend;
import com.ship.boats.domain.SpBoatsSisterManage;
import com.ship.boats.domain.vo.*;
import com.ship.boats.mapper.BoatsArchivesMapper;
import com.ship.boats.mapper.SpBoatsPscInspectMapper;
import com.ship.boats.service.*;
import com.ship.common.core.constant.ShipApiConstants;
import com.ship.common.core.exception.ServiceException;
import com.ship.common.core.utils.StringUtils;
import com.ship.common.core.utils.bean.BeanUtils;
import com.ship.common.core.web.domain.BaseResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <b>BoatsArchivesServiceImpl</b>
 *
 * @description: BoatsArchivesServiceImpl <br>
 * @date: 2024/3/28 16:05 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class BoatsArchivesServiceImpl extends ServiceImpl<BoatsArchivesMapper, IhsShipBase> implements BoatsArchivesService {
    private static final Logger logger = LoggerFactory.getLogger(BoatsArchivesServiceImpl.class);

    @Autowired
    private BoatsArchivesMapper boatsArchivesMapper;

    @Autowired
    private SpBoatsPscInspectMapper spBoatsPscInspectMapper;

    @Autowired
    private BoatsMmsiChangeService boatsMmsiChangeService;

    @Autowired
    private SpBoatsSisterManageService spBoatsSisterManageService;

    @Autowired
    private SpBoastPortMessageService spBoastPortMessageService;

    @Autowired
    private BoatsArchivesExtendService boatsArchivesExtendService;

    @Autowired
    private ConShippingService conShippingService;

    @Autowired
    private BoatsShipCountService boatsShipCountService;

    @Autowired
    private BoatsSystemServiceImpl boatsSystemServiceImpl;


    @Override
    public boolean getBoatsArchives(List<BoatsArchivesInfo> archivesList) {
        boolean status = true;
        if (CollectionUtil.isNotEmpty(archivesList)){
            archivesList.forEach(item -> {
                //根据imo及船舶名称查询船舶信息
                IhsShipBase shipBase = baseMapper.queryShipByName(item.getShipName(),item.getImo());
                IhsShipBase ihsShipBase = new IhsShipBase();
                BeanUtils.copyProperties(item,ihsShipBase);
                if (null != shipBase){
                    if (StringUtils.isNotEmpty(item.getMmsi()) && !item.getMmsi().equals(shipBase.getMmsi())){
                        boatsMmsiChangeService.createMmsiChange(item.getMmsi(),item.getImo(),item.getShipName(),new Date());
                    }
                    ihsShipBase.setCreateTime(new Date());
                    ihsShipBase.setUpdateTime(new Date());
                    boatsArchivesMapper.deleteShipBase(item.getImo());
                    boatsArchivesMapper.createIhsShipBase(ihsShipBase);
                }else {
                    ihsShipBase.setUpdateTime(new Date());
                    ihsShipBase.setCreateTime(new Date());
                    boatsArchivesMapper.createIhsShipBase(ihsShipBase);
                    //同步船运合同数据
                    conShippingService.updateConShipping(ihsShipBase);
                    SpBoatsArchivesExtend spBoatsArchivesExtend = new SpBoatsArchivesExtend();
                    spBoatsArchivesExtend.setImo(item.getImo());
                    spBoatsArchivesExtend.setShipName(item.getShipName());
                    spBoatsArchivesExtend.setMmsi(item.getMmsi());
                    spBoatsArchivesExtend.setShipTypeGroup(item.getShipTypeGroup());
                    spBoatsArchivesExtend.setOperator(item.getOperator());
                    Snowflake snowflake = new Snowflake(1, 1);
                    Long snowflakeId = snowflake.nextId();
                    spBoatsArchivesExtend.setId(snowflakeId);
                    boatsArchivesExtendService.addBoatsArchives(spBoatsArchivesExtend);

                }
            });
        }
        Integer countTotal = boatsArchivesMapper.countTotal();
        boatsShipCountService.createShipCount(countTotal);
        return status;
    }

    @Override
    public boolean getBoatsDockWith() {
        //查询所有船舶mmsi信息列表
        List<QueryBoatsMessageInfo> shipBases = baseMapper.queryShipBaseAll();
        shipBases.forEach(item -> {
            List<SpBoastPortMessage> boatsPortMessageList = new ArrayList<>();
            Map<String,String> map = new HashMap<>();
            if (!Objects.equals(item.getMmsi(), "")) {
                map.put("mmsiList", item.getMmsi());
                Object boatsUtil = boatsSystemServiceImpl.getBoatsUtil(map, ShipApiConstants.QUERY_BOATS_ID_URL);
                List<QueryBoatsInfo> boatsList = JSONUtil.toList(JSONUtil.parseArray(boatsUtil), QueryBoatsInfo.class);
                if (CollectionUtil.isNotEmpty(boatsList)) {
                    QueryBoatsInfo queryBoatsDockWithInfo = boatsList.get(0);
                    Map<String, String> dockWithMap = new HashMap<>();
                    dockWithMap.put("shipId", queryBoatsDockWithInfo.getShipId());
                    dockWithMap.put("timeFlag", "1");
                    Object boatsDockWith = boatsSystemServiceImpl.getBoatsUtil(dockWithMap, ShipApiConstants.QUERY_BOATS_HISTORY_DOCK_WITH_URL);
                    if (null != boatsDockWith) {
                        Map<String, Object> boatsMap = (Map) com.alibaba.fastjson.JSONObject.toJSON(JSONUtil.parse(boatsDockWith));
                        List<PortHisItemsInfo> dockWithList = JSONUtil.toList(JSONUtil.parseArray(boatsMap.get("portHisItems")), PortHisItemsInfo.class);
                        if (CollectionUtil.isNotEmpty(dockWithList)) {
                            dockWithList.forEach(dockWith -> {
                                SpBoastPortMessage spBoastPortMessage = new SpBoastPortMessage();
                                spBoastPortMessage.setImo(item.getImo());
                                spBoastPortMessage.setShipName(item.getShipName());
                                spBoastPortMessage.setShipId((String) boatsMap.get("shipId"));
                                if (StringUtils.isNotEmpty(dockWith.getInTime())) {
                                    spBoastPortMessage.setInTime(conversionTime(dockWith.getInTime()));
                                }
                                if (StringUtils.isNotEmpty(dockWith.getOutTime())) {
                                    spBoastPortMessage.setOutTime(conversionTime(dockWith.getOutTime()));
                                }
                                spBoastPortMessage.setPortNameEn(dockWith.getPortNameEn());
                                spBoastPortMessage.setPortNameChs(dockWith.getPortNameChs());
                                spBoastPortMessage.setCountryEn(dockWith.getCountryEn());
                                spBoastPortMessage.setCountryChs(dockWith.getCountryChs());
                                Integer inPortDraught = queryBoatsDraught(item.getMmsi(), dockWith.getInTime());
                                Integer outPortDraught = queryBoatsDraught(item.getMmsi(), dockWith.getOutTime());
                                spBoastPortMessage.setInPortDraught(inPortDraught);
                                spBoastPortMessage.setOutPortDraught(outPortDraught);
                                if (StringUtils.isNotEmpty(dockWith.getOutTime()) && StringUtils.isNotEmpty(dockWith.getInTime())) {
                                    Integer time = (Integer.valueOf(dockWith.getOutTime()) - Integer.valueOf(dockWith.getInTime()));
                                    Integer hours = time / 3600;
                                    spBoastPortMessage.setLayUpTime(time);
                                }
                                spBoastPortMessage.setSisterStatus("0");
                                spBoastPortMessage.setEnable("1");
                                spBoastPortMessage.setCreateTime(new Date());
                                spBoastPortMessage.setUpdateTime(new Date());
                                boatsPortMessageList.add(spBoastPortMessage);
                            });
                        }
                    }
                }
                //查询姊妹船信息
                Map<String, String> sisterMap = new HashMap<>();
                sisterMap.put("imo", item.getImo());
                Object obj = boatsSystemServiceImpl.getSisterImoUtil(sisterMap, ShipApiConstants.QUERY_SISTERIMO_URL);
                List<QueryBoatsSisterShipInfo> sisterShipList = JSONUtil.toList(JSONUtil.parseArray(obj), QueryBoatsSisterShipInfo.class);
//            logger.info("查询姊妹船返回结果:{}"+JSONUtil.parse(sisterShipList));
                List<SpBoatsSisterManage> sisterShips = new ArrayList<>();
                if (CollectionUtil.isNotEmpty(sisterShipList)) {
                    sisterShipList.forEach(sisterShip -> {
                        if (StringUtils.isNotEmpty(sisterShip.getLinkedImo())) {
                            SpBoatsSisterManage spBoatsSisterManage = new SpBoatsSisterManage();
                            spBoatsSisterManage.setShipName(item.getShipName());
                            spBoatsSisterManage.setImo(item.getImo());
                            spBoatsSisterManage.setSisterImo(sisterShip.getLinkedImo());
                            spBoatsSisterManage.setEnable("1");
                            spBoatsSisterManage.setCreateTime(new Date());
                            spBoatsSisterManage.setUpdateTime(new Date());
                            sisterShips.add(spBoatsSisterManage);
                        }
                    });
                }
                spBoatsSisterManageService.renewalSisterShipByImo(sisterShips);
                if (CollectionUtil.isNotEmpty(sisterShips) && CollectionUtil.isNotEmpty(boatsPortMessageList)) {
                    boatsPortMessageList.forEach(portMessage -> {
                        portMessage.setSisterStatus("1");
                    });
                }
                if (CollectionUtil.isNotEmpty(boatsPortMessageList)) {
                    //船舶挂靠数据
                    spBoastPortMessageService.renewalBoatsPortMessageByImo(item.getImo(), boatsPortMessageList);
                }
            }
        });
        return true;
    }

    @Override
    public void getBoatsSister(){
        List<QueryBoatsMessageInfo> shipBases = baseMapper.queryShipBaseAll();
        shipBases.forEach(item -> {
            //查询姊妹船信息
            Map<String,String> sisterMap = new HashMap<>();
            sisterMap.put("imo",item.getImo());
            Object obj = boatsSystemServiceImpl.getSisterImoUtil(sisterMap, ShipApiConstants.QUERY_SISTERIMO_URL);
            List<QueryBoatsSisterShipInfo> sisterShipList = JSONUtil.toList(JSONUtil.parseArray(obj), QueryBoatsSisterShipInfo.class);
            logger.info("查询姊妹船返回结果:{}"+JSONUtil.parse(sisterShipList));
            List<SpBoatsSisterManage> sisterShips = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(sisterShipList)){
                sisterShipList.forEach(sisterShip -> {
                    if (StringUtils.isNotEmpty(sisterShip.getLinkedImo())) {
                        SpBoatsSisterManage spBoatsSisterManage = new SpBoatsSisterManage();
                        spBoatsSisterManage.setShipName(item.getShipName());
                        spBoatsSisterManage.setImo(item.getImo());
                        spBoatsSisterManage.setSisterImo(sisterShip.getLinkedImo());
                        spBoatsSisterManage.setEnable("1");
                        spBoatsSisterManage.setCreateTime(new Date());
                        spBoatsSisterManage.setUpdateTime(new Date());
                        sisterShips.add(spBoatsSisterManage);
                    }
                });
            }
            spBoatsSisterManageService.renewalSisterShipByImo(sisterShips);
        });
    }

    @Override
    public List<QueryBoatsSisterInfo> queryBoatsSisterList(List<String> imoList) {
        return baseMapper.queryBoatsSisterList(imoList);
    }

    @Override
    public List<SpBoatsArchivesExtend> queryShipTypeGroupAll() {
        return baseMapper.queryShipTypeGroupAll();
    }

    public Date conversionTime(String time){
        // 将UTC秒转换为Instant
        Instant instant = Instant.ofEpochSecond(Integer.valueOf(time));

        // 转换Instant为ZonedDateTime，默认时区（例如America/New_York）
        ZonedDateTime zonedDateTime = instant.atZone(ZoneId.systemDefault());
        // 格式化ZonedDateTime为字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = zonedDateTime.format(formatter);
        Date date = DateUtil.parse(formattedDateTime, DatePattern.NORM_DATETIME_FORMATTER);
        return date;
    }

    //根据imo号查询吃水深度
    public Integer queryBoatsDraught(String mmsi,String time){
        if (StringUtils.isNotEmpty(time)){
            Map<String,String> queryMap = new HashMap<>();
            queryMap.put("mmsi",mmsi);
            queryMap.put("time",time);
            Object boatsDraught = boatsSystemServiceImpl.getBoatsUtil(queryMap, ShipApiConstants.QUERY_BOATS_DRAUGHT_URL);
            if (!JSONUtil.isNull(boatsDraught)){
                Map<String,Integer> map = JSONUtil.toBean(JSONUtil.parseObj(boatsDraught), Map.class);
                if (null != map.get("draught")){
                    return map.get("draught");
                }
            }
        }
        return 0;
    }

    @Override
    public List<String> queryImoList() {
        return baseMapper.queryImoList();
    }

    @Override
    public List<String> queryShipTypeGroup() {
        return baseMapper.queryShipTypeGroup();
    }

    @Override
    public IhsShipBase queryShipBaseByImo(String imo) {
        return baseMapper.queryShipBaseByImo(imo);
    }


    @Override
    public List<String> queryMmsiList() {
        return baseMapper.queryMmsiList();
    }
}
